package com.example.internetserverhttps.slice;

import com.example.internetserverhttps.InfoWeather;
import com.example.internetserverhttps.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import ohos.utils.zson.ZSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class WeatherPageSlice extends AbilitySlice {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, "WeatherPageSlice.class");

    EventHandler eventHandler = new EventHandler(EventRunner.create("queryNetWork"));

    private TextField mTextFeild;

    private Text mCity;       //城市
    private Text mReason;       //返回说明
    private Text mInfo;       //天气情况
    private Text mWid;       //天气标识id
    private Text mHumidity;       //温度
    private Text mTemperature;       //湿度
    private Text mDirect;       //风向
    private Text mPower;       //风力
    private Text mAqi;       //空气指数

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_weather_page);


        mTextFeild = findComponentById(ResourceTable.Id_textfield_city);
        findComponentById(ResourceTable.Id_query_btn)
                .setClickedListener(component -> queryWeather());

        mCity = findComponentById(ResourceTable.Id_text_city);
        mReason = findComponentById(ResourceTable.Id_text_reason);
        mInfo = findComponentById(ResourceTable.Id_text_info);
        mWid = findComponentById(ResourceTable.Id_text_wid);
        mHumidity = findComponentById(ResourceTable.Id_text_humidity);
        mTemperature = findComponentById(ResourceTable.Id_text_temperature);
        mDirect = findComponentById(ResourceTable.Id_text_direct);
        mPower = findComponentById(ResourceTable.Id_text_power);
        mAqi = findComponentById(ResourceTable.Id_text_aqi);


    }

    /**
     * 查询手机信息
     */
    private void queryWeather() {
        String text = mTextFeild.getText();

        if (text == null) {
            new ToastDialog(getContext()).setText("请输入城市名").show();
            return;
        }
        NetManager netManager = NetManager.getInstance(getContext());
        // 判断对象是否有网络
        if (!netManager.hasDefaultNet()) {
            new ToastDialog(getContext()).setText("无网络").show();
            return;
        }

//  在不是UI线程里面进行网络操作
        eventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                // 获取当前网络
                NetHandle net = netManager.getDefaultNet();
                netManager.addDefaultNetStatusCallback(netStatusCallback);

                HttpURLConnection connection = null;

                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                    String url = "http://apis.juhe.cn/simpleWeather/query?city=" + text + "&key=0e3a542fd95b1c8ea69ac13e63cfdb7c";
                    HiLog.info(LABEL_LOG, url);
                    URL url1 = new URL(url);

                    URLConnection urlConnection = net.openConnection(url1);

                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }

                    // 设置以 “GET” 为请求方式
                    connection.setRequestMethod("GET");

                    // 连接
                    connection.connect();

                    // 获取服务器返回的数据
                    InputStream inputStream = urlConnection.getInputStream();

                    byte[] bytes = new byte[2 * 1024];
                    int read = inputStream.read(bytes);

                    while (read != -1) {
                        outputStream.write(bytes, 0, read);

                        read = inputStream.read(bytes);
                    }

                    String result = new String(outputStream.toByteArray());

                    getUITaskDispatcher().syncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            disPlayData(result);
                        }
                    });


                    HiLog.info(LABEL_LOG, result);
                } catch (IOException e) {

                }


            }
        });

    }

    private void disPlayData(String result) {
        InfoWeather infoWeather = ZSONObject.stringToClass(result, InfoWeather.class);

        if (infoWeather.getError_code() == 0) {
            new ToastDialog(getContext()).setText("请求成功").show();

            InfoWeather.Result result1 = infoWeather.getResult();
            InfoWeather.Result.Realtime realtime = result1.getRealtime();

            mCity.setText("城市："+ result1.getCity());
            mReason.setText("查询情况：" + infoWeather.getReason());
            mInfo.setText("天气情况：" + realtime.getInfo());
            mWid.setText("天气标识id：" + realtime.getWid());
            mHumidity.setText("湿度：" + realtime.getHumidity());
            mTemperature.setText("温度：" + realtime.getTemperature());
            mDirect.setText("风向：" + realtime.getDirect());
            mPower.setText("风力：" + realtime.getPower());
            mAqi.setText("空气指数：" + realtime.getAqi());

            HiLog.info(LABEL_LOG, result1.toString());

        } else {
            new ToastDialog(getContext()).setText("出错了").show();
            return;
        }


    }

    /**
     * 当前网络变化
     */
    NetStatusCallback netStatusCallback = new NetStatusCallback() {
        @Override
        public void onAvailable(NetHandle handle) {
            super.onAvailable(handle);
        }

        @Override
        public void onBlockedStatusChanged(NetHandle handle, boolean blocked) {
            super.onBlockedStatusChanged(handle, blocked);
        }
    };


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
